package cn.hzking.gjmall.delegates.main;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.fingdo.statelayout.StateLayout;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.hzking.gjmall.R;
import cn.hzking.gjmall.activitys.second.CateGoryGoodListActivity;
import cn.hzking.gjmall.activitys.second.SearchActivity;
import cn.hzking.gjmall.base.BaseDelegate;
import cn.hzking.gjmall.bean.CategoryBean;
import cn.hzking.gjmall.delegates.category.CategoryContentDelegate;
import cn.hzking.gjmall.net.RetrofitFactory;
import cn.hzking.gjmall.net.base.BaseObserver;
import cn.hzking.gjmall.utils.Logger;
import cn.hzking.gjmall.utils.SwipeRefreshLayoutUtils;
import me.yokeyword.fragmentation.SupportFragment;

/**
 * A simple {@link Fragment} subclass.
 */
public class CategoryDelegate extends BaseDelegate {


    @Bind(R.id.category_search)
    RelativeLayout categorySearch;
    @Bind(R.id.vertical_list_container)
    LinearLayout verticalListContainer;
    @Bind(R.id.sort_content_container)
    FrameLayout sortContentContainer;
    @Bind(R.id.category_scrollview)
    ScrollView scrollView;
    @Bind(R.id.refrsh)
    SwipeRefreshLayout refrsh;
    @Bind(R.id.statlayout_cate)
    StateLayout stateLayout;
    private LayoutInflater inflater;
    private TextView toolsTextViews[]; //textview的集合
    private View views[];   //整个view的集合
    private int scrllViewWidth = 0, scrollViewMiddle = 0;
    private ViewPager shop_pager;
    private int firstId = 0; //一级条目的id
    private Gson gson;
    private String cacheContentData = null;//缓存在二级页面要显示的数据
    private int cachellId = -1; //一级条目在Linnerlayout中的位置
    private int cacheLastllId = -1;//点全部按钮前的那个按钮的id
    private ArrayList<String> itemList = new ArrayList<>();//需要传给列表页的名称
    private ArrayList<String> categoryIds = new ArrayList<>();//一级条目的id集合

    public CategoryDelegate() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Logger.e("分类onCreat");
    }

    @Override
    public Object setLayout() {
        Logger.e("分类onCreatView");
        return R.layout.fragment_category_delegate;
    }

    @Override
    public void onBindView(@Nullable final Bundle savedInstanceState, View rootView) {
        Logger.e("分类onBindView");
        EventBus.getDefault().register(this);
        SwipeRefreshLayoutUtils.initRefreshLayout(refrsh);
        gson = new Gson();
        refrsh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                initData(_mActivity, false, false, savedInstanceState, true);

            }
        });


    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Logger.e("分类onActivityCreated");


    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        Logger.e("分类onLazyInitView");
        initData(_mActivity, true, true, savedInstanceState, false);

    }

    private void initData(Activity context, boolean isShowDilog, final boolean isCancel, final Bundle savedInstanceState, final boolean isRemove) {
        RetrofitFactory.getInstant()
                .API()
                .getCateGoryData()
                .compose(this.<CategoryBean>setThread())
                .subscribe(new BaseObserver<CategoryBean>(context, isShowDilog, isCancel) {
                    @Override
                    protected void onRequestStart() {
                        super.onRequestStart();
                        stateLayout.showContentView();
                    }

                    @Override
                    protected void onSuccees(CategoryBean categoryBean) throws Exception {
                        Logger.e("请求");
                        List<CategoryBean.DataBean.CateListBean> cateList = categoryBean.getData().getCateList();
                        showToolsView(savedInstanceState, cateList, isRemove);
                        CategoryBean.DataBean.CateListBean bean = cateList.get(1);
                        String contentString = gson.toJson(bean);
                        cacheContentData = contentString;
                        if (findChildFragment(CategoryContentDelegate.class) == null) {//fragment的没有缓存的时候
                            if (savedInstanceState == null) {//正常启动
                                Logger.e("正常启动");
                                cachellId = 1;
                                changeTextColor(cachellId);//改变字体颜色
                                loadRootFragment(R.id.sort_content_container, CategoryContentDelegate.newInstance(cateList.get(1).getId(), contentString));
                            } else {//异常销毁
                                Logger.e("异常销毁");
                                firstId = savedInstanceState.getInt("id");
                                cachellId = savedInstanceState.getInt("cachellId");
                                cacheContentData = savedInstanceState.getString("contentString");
                                changeTextColor(cachellId);//改变字体颜色
                                loadRootFragment(R.id.sort_content_container, CategoryContentDelegate.newInstance(firstId, cacheContentData));
                            }
                        } else {//fragment有缓存的时候

                            if (isRemove) {//刷新
                                Logger.e("刷新");
                                cachellId = 1;
                                changeTextColor(cachellId);//改变字体颜色
                                switchContentFragment(CategoryContentDelegate.newInstance(cateList.get(1).getId(), contentString));

                            } else {//异常销毁
                                if (savedInstanceState == null) {//刷新
                                    Logger.e("异常销毁");
                                    firstId = savedInstanceState.getInt("id");
                                    cachellId = savedInstanceState.getInt("cachellId");
                                    cacheContentData = savedInstanceState.getString("contentString");
                                    changeTextColor(cachellId);//改变字体颜色
                                    switchContentFragment(CategoryContentDelegate.newInstance(firstId, cacheContentData));
                                }

                            }


                        }

                    }

                    @Override
                    protected void onFailure(Throwable e, boolean isNetWorkError) throws Exception {
                        View view = View.inflate(mActivity, R.layout.layout_statelayout_custom_error1, null);
                        stateLayout.showCustomView(view);

                    }

                    @Override
                    protected void onRequestEnd() {
                        if (refrsh != null) {
                            refrsh.setRefreshing(false);
                        }
                        super.onRequestEnd();
                    }
                });
    }

    @Override
    public void onResume() {
        super.onResume();


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Logger.e("分类onHiddenChanged");


    }

    /**
     * 替换加载 内容Fragment
     *
     * @param fragment
     */
    public void switchContentFragment(CategoryContentDelegate fragment) {
        SupportFragment contentFragment = findChildFragment(CategoryContentDelegate.class);
        if (contentFragment != null) {
            contentFragment.replaceFragment(fragment, false);
        }
    }

    /**
     * 动态生成显示items中的textview
     */
    private void showToolsView(Bundle savedInstanceState, List<CategoryBean.DataBean.CateListBean> nameList, boolean isRemove) {
        CategoryBean.DataBean.CateListBean bean1 = new CategoryBean.DataBean.CateListBean();
        bean1.setName("全部");
        bean1.setId(-1);
        itemList.clear();
        categoryIds.clear();
        nameList.add(0, bean1);
        for (int i = 0; i < nameList.size(); i++) {
            itemList.add(nameList.get(i).getName());
            categoryIds.add(String.valueOf(nameList.get(i).getId()));

        }

        if (verticalListContainer != null && isRemove) {//刷新的时候要清空数据
            verticalListContainer.removeAllViews();
        }
        inflater = LayoutInflater.from(_mActivity);
        toolsTextViews = new TextView[nameList.size()];
        views = new View[nameList.size()];
        for (int i = 0; i < nameList.size(); i++) {
            View view = inflater.inflate(R.layout.item_category_list, null);
            CategoryBean.DataBean.CateListBean bean = nameList.get(i);
            bean.setLlId(i);//在布局中的位置
            view.setTag(bean);
            TextView textView = view.findViewById(R.id.category_list_text);
            view.setOnClickListener(toolsItemListener);
            textView.setText(bean.getName());
            verticalListContainer.addView(view);
            toolsTextViews[i] = textView;
            views[i] = view;
        }
        if (savedInstanceState == null) {//正常情况
            changeTextColor(1);
        } else {//异常销毁情况
            int llId = savedInstanceState.getInt("cachellId");
            changeTextColor(llId);
        }
    }

    private View.OnClickListener toolsItemListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            CategoryBean.DataBean.CateListBean bean = (CategoryBean.DataBean.CateListBean) v.getTag();
            int llId = bean.getLlId();
            int id = bean.getId();
            changeTextColor(llId);
            changeTextLocation(llId);
            firstId = id;
            if(cachellId != 0) {//前面一次点击的不是全部
                cacheLastllId = cachellId;
            }
            cachellId = llId;
            if (llId == 0) {//点击的是全部的时候
                Intent intent = new Intent(_mActivity, CateGoryGoodListActivity.class);
                intent.putExtra("type", 0);//一级条目点击进入
                intent.putStringArrayListExtra("itemContent", itemList);//内容
                intent.putStringArrayListExtra("categoryId", categoryIds);//一级条目id
                startActivity(intent);

            } else {//点击的是子条目的时候
                String contentString = gson.toJson(bean);
                cacheContentData = contentString;
                switchContentFragment(CategoryContentDelegate.newInstance(id, contentString));
            }

        }
    };

    /**
     * 改变textView的颜色
     *
     * @param id 点击了的textview
     */
    private void changeTextColor(int id) {
        for (int i = 0; i < toolsTextViews.length; i++) {
            if (i != id) {//没选中
                toolsTextViews[i].setBackgroundResource(android.R.color.transparent);
                toolsTextViews[i].setTextColor(0XffB9A287);
            }
        }
        toolsTextViews[id].setBackgroundResource(android.R.color.white);
        toolsTextViews[id].setTextColor(Color.BLACK);
    }

    /**
     * 改变栏目位置
     *
     * @param clickPosition
     */
    private void changeTextLocation(int clickPosition) {

        int x = (views[clickPosition].getTop() - getScrollViewMiddle() + (getViewheight(views[clickPosition]) / 2));
        scrollView.smoothScrollTo(0, x);
    }

    /**
     * 返回scrollview的中间位置
     *
     * @return
     */
    private int getScrollViewMiddle() {
        if (scrollViewMiddle == 0)
            scrollViewMiddle = getScrollViewheight() / 2;
        return scrollViewMiddle;
    }

    /**
     * 返回ScrollView的宽度
     *
     * @return
     */
    private int getScrollViewheight() {
        if (scrllViewWidth == 0)
            scrllViewWidth = scrollView.getBottom() - scrollView.getTop();
        return scrllViewWidth;
    }

    /**
     * 返回view的宽度
     *
     * @param view
     * @return
     */
    private int getViewheight(View view) {
        return view.getBottom() - view.getTop();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("id", firstId);
        outState.putString("contentString", cacheContentData);
        outState.putInt("cachellId", cachellId);
    }

    @OnClick(R.id.category_search)
    public void search(View view) {
        Intent intent = new Intent(_mActivity, SearchActivity.class);
        startActivity(intent);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(String s) {
        if ("返回".equals(s)) {
            changeTextColor(cacheLastllId);

        }

    }

}
